class GamePlayUI extends eui.Component implements  eui.UIComponent {

	private return_btn:eui.Image;
	private img_header:eui.Image;
	private lab_userID:eui.Label;

	private player1_num:eui.Label;
	private player2_num:eui.Label;
	private player3_num:eui.Label;
	private player2_name:eui.Label;
	private player3_name:eui.Label;
	private submit_btn:eui.Button;

	private isSubmit:boolean = false;

	private game_result:eui.Label;



	public constructor() {
		super();
		console.log(GameData.playerUserIds);
	}

	protected partAdded(partName:string,instance:any):void
	{
		this.getChilds(partName,instance);
		super.partAdded(partName,instance);
	}

	private getChilds(partName:string,instance:any):void{
		switch(partName){
			case "game_result":
				this.game_result = instance;
				break;
			case "player1_num":
				this.player1_num = instance;
				break;
			case "player2_num":
				this.player2_num = instance;
				break;
			case "player3_num":
				this.player3_num = instance;
				break;
			case "player2_name":
				this.player2_name = instance;
				break;
			case "player3_name":
				this.player3_name = instance;
				break;
			case "submit_btn":
				this.submit_btn = instance;
				this.submit_btn.addEventListener(egret.TouchEvent.TOUCH_TAP, this.submitData, this);
				break;
			case "img_header":
				this.img_header = instance;
				this.img_header.source = GameData.gameUser.avatar;
				break;
			case "lab_userID":
				this.lab_userID = instance;
				this.lab_userID.text ="用户："+GameData.gameUser.id+"\n"+GameData.gameUser.name;
				break;
			case "return_btn":
                this.return_btn = instance;
                //this.return_btn.addEventListener(egret.TouchEvent.TOUCH_TAP, this.mbuttonLeaveRoom, this);
			default:
				break;
		}
	}
	protected childrenCreated():void
	{
		super.childrenCreated();
		//注册matchvs网络监听事件
		this.addMsResponseListen();
		this.initView();
	}
	public initView(){
		for(let i=0;i<GameData.playerUserIds.length;i++){
			if(GameData.playerUserIds[i].tableID == 2){
				this.player2_name.text = GameData.playerUserIds[i].name;
			}else if(GameData.playerUserIds[i].tableID == 3){
				this.player3_name.text = GameData.playerUserIds[i].name;
			}
		}
	}
	private submitData(){
		console.log("点击提交数据按钮");
		this.isSubmit = true;
		this.submit_btn.enabled = false;
		let num = this.getRandomInt(1,50);
		console.log("提交数据：" + num);
		GameData.gameUser.pValue = num;
		//发送游戏数据
		let data:any = {
			action:1,
			id:GameData.gameUser.id,
			name:GameData.gameUser.name,
			pValue:GameData.gameUser.pValue
		};
		for(let i = 0; i < GameData.playerUserIds.length; i++){
			if(GameData.playerUserIds[i].id == GameData.gameUser.id){
				GameData.playerUserIds[i].pValue = num;
			}
		}
		let result = mvs.MsEngine.getInstance.sendEvent(JSON.stringify(data));
		if (!result || result.result !== 0) {
			this.player1_num.text = "异常：" + result;
			console.log('玩家提交数据失败，result：' + result);
		}else{
			this.player1_num.text = num.toString();
			console.log('玩家提交数据成功，submitData：' + data);
			
		}
		this.checkFinish();
		
	}
	private getRandomInt(min: number, max: number): number {  
		var Range = max - min;  
		var Rand = Math.random();  
		return(min + Math.round(Rand * Range));  
	}
	/**
	 * 收到消息事件，修改数据
	 */
	private sendEventNotify(event:egret.Event) {
		let data = JSON.parse(event.data.cpProto);
		console.log("进入sendEventNotify方法，");
		console.log(event);
		if(1 == data.action){
			for(let i = 0; i < GameData.playerUserIds.length; i++){
				
				if(GameData.playerUserIds[i].id == data.id){
					GameData.playerUserIds[i].pValue = data.pValue;
				}
				if(GameData.playerUserIds[i].id != GameData.gameUser.id && GameData.playerUserIds[i].pValue > 0){
					if(GameData.playerUserIds[i].tableID == 2){
						this.player2_num.text = GameData.playerUserIds[i].pValue.toString();
						this.player2_name.text = GameData.playerUserIds[i].name;
					}else if(GameData.playerUserIds[i].tableID == 3){
						this.player3_num.text = GameData.playerUserIds[i].pValue.toString();
						this.player3_name.text = GameData.playerUserIds[i].name;
					}
				}
			}
			this.checkFinish();
			
		}
		
		//发送游戏数据
		// let data:any = {
		// 	id:GameData.gameUser.id,
		// 	pValue:GameData.gameUser.pValue
		// };
		// let result = mvs.MsEngine.getInstance.sendEvent(JSON.stringify(data));
		// if (!result || result.result !== 0) {
		// 	return console.log('重连事件发送失败');
		// }
        
	}
	private checkFinish(){
		let num = 0;
		let winner = GameData.playerUserIds[0];
		for(let i = 0; i < GameData.playerUserIds.length; i++){
			if(winner.pValue < GameData.playerUserIds[i].pValue){//计算胜利者
				winner = GameData.playerUserIds[i];
			}
			if(GameData.playerUserIds[i].pValue > 0){
				num++;
			}
		}
		if(num == 3){
			console.log("游戏结束了");
			//GameSceneView._gameScene.showResult(winner);
			this.game_result.text = "恭喜" + winner.name + "获得了最后的胜利,得分：" + winner.pValue;
		//	Toast.show("恭喜" + '' + "获得了最后的胜利");
		}
	}
	/**
	 * 离开房间异步回调
	 */
	private leaveRoomNotify(ev:egret.Event) {
		GameData.isGameOver = true;
		this.release();
		console.log("2结束房间ID：",  GameData.roomID, GameData.playerUserIds);
		//GameSceneView._gameScene.showResult(GameData.playerUserIds,this._roomID);
	}
	/**
	 * 收到其他玩家的网络状态情况
	 */
	private networkStateNotify(ev:egret.Event){
		let netnotify = ev.data;
		console.log("玩家："+netnotify.userID+" state:"+netnotify.state);
		if(netnotify.state === 1){
			//this._netWorkNoticeLabel.text = "玩家掉线:"+netnotify.userID;
			console.log("玩家掉线:"+netnotify.userID);
		}else if(netnotify.state === 2 ){
			console.log("玩家已经重连进来");
			//this._netWorkNoticeLabel.text = "";
		}else{
			console.log("玩家："+ netnotify.userID+" 重新连接失败！离开房间，游戏结束");
			mvs.MsEngine.getInstance.leaveRoom("玩累了");
			this.release();
			GameSceneView._gameScene.lobby();
			GameData.isGameOver = true;
			GameData.isRoomOwner = false;
			GameData.syncFrame = false;
		}

	}
	/**
	 * 设置帧同步
	 */
	private setFrameSyncResponse(ev:egret.Event) {
		let rsp = ev.data;
		if(rsp.mStatus == 200) {
			console.log("设置帧同步率成功");
		} else {
			console.log("设置帧同步率失败");
		}
	}
	/**
	 * 帧同步更新
	 */
	private frameUpdate(ev:egret.Event) {
		let data = ev.data;
		
		console.log("帧同步更新,frameUpdate");
	}
	/**
	 * 注册 matchvs 组件监听事件
	 */
	private addMsResponseListen(){
		//this.moveTimeer.addEventListener(egret.TimerEvent.TIMER,this.RoleMoveFun,this);
        //发送消息
        mvs.MsResponse.getInstance.addEventListener(mvs.MsEvent.EVENT_SENDEVENT_NTFY, this.sendEventNotify,this);
        //离开房间
        mvs.MsResponse.getInstance.addEventListener(mvs.MsEvent.EVENT_LEAVEROOM_NTFY, this.leaveRoomNotify,this);

		mvs.MsResponse.getInstance.addEventListener(mvs.MsEvent.EVENT_NETWORKSTATE_NTFY, this.networkStateNotify,this);

		mvs.MsResponse.getInstance.addEventListener(mvs.MsEvent.EVENT_SETFRAMESYNC_RSP, this.setFrameSyncResponse,this);
		mvs.MsResponse.getInstance.addEventListener(mvs.MsEvent.EVENT_FRAMEUPDATE, this.frameUpdate,this);
    }

    public release(){
		//this.moveTimeer.removeEventListener(egret.TimerEvent.TIMER,this.RoleMoveFun,this);
        mvs.MsResponse.getInstance.removeEventListener(mvs.MsEvent.EVENT_SENDEVENT_NTFY, this.sendEventNotify,this);

        mvs.MsResponse.getInstance.removeEventListener(mvs.MsEvent.EVENT_LEAVEROOM_NTFY, this.leaveRoomNotify,this);

		mvs.MsResponse.getInstance.removeEventListener(mvs.MsEvent.EVENT_NETWORKSTATE_NTFY, this.networkStateNotify,this);

		mvs.MsResponse.getInstance.removeEventListener(mvs.MsEvent.EVENT_SETFRAMESYNC_RSP, this.setFrameSyncResponse,this);
		mvs.MsResponse.getInstance.removeEventListener(mvs.MsEvent.EVENT_FRAMEUPDATE, this.frameUpdate,this);
    }
}